/**
 * RSS阅读器状态管理Store
 * 使用Pinia管理RSS源、文章、分类等核心状态
 */

import { defineStore } from 'pinia';
import type { RSSFeed, Article, Category, SearchFilter, UserSettings } from '@/types';
import { feedsApi, articlesApi, dataTransform } from '@/services/api';

/**
 * RSS Store状态接口定义
 * @interface RSSStoreState
 */
interface RSSStoreState {
  // RSS源相关状态
  /** RSS源列表 */
  feeds: RSSFeed[];
  /** 当前选中的RSS源ID */
  selectedFeedId: string | null;
  /** RSS源加载状态 */
  feedsLoading: boolean;
  
  // 文章相关状态
  /** 文章列表 */
  articles: Article[];
  /** 当前选中的文章ID */
  selectedArticleId: string | null;
  /** 文章加载状态 */
  articlesLoading: boolean;
  /** 文章总数 */
  totalArticles: number;
  /** 当前页码 */
  currentPage: number;
  
  // 分类相关状态
  /** 分类列表 */
  categories: Category[];
  /** 当前选中的分类ID */
  selectedCategoryId: string | null;
  
  // 搜索和过滤状态
  /** 搜索过滤器 */
  searchFilter: SearchFilter;
  
  // 用户设置
  /** 用户设置 */
  settings: UserSettings;
}

/**
 * 默认用户设置
 */
const defaultUserSettings: UserSettings = {
  theme: 'light',
  language: 'zh-CN',
  autoRefresh: true,
  refreshInterval: 30,
  notificationsEnabled: true,
  showUnreadOnly: false,
  articlesPerPage: 20,
  defaultView: 'list',
  fontSize: 'medium',
  readingMode: 'comfortable',
  markAsReadOnScroll: true,
  openLinksInNewTab: true,
  enableKeyboardShortcuts: true,
  compactMode: false,
  showImages: true,
  enableDarkMode: false,
  autoMarkAsRead: false,
  syncSettings: true,
};

/**
 * 默认搜索过滤器
 */
const defaultSearchFilter: SearchFilter = {
  keyword: '',
  feedIds: [],
  categoryIds: [],
  unreadOnly: false,
  favoriteOnly: false,
  sortBy: 'publishedAt',
  sortOrder: 'desc',
};

/**
 * 生成唯一ID
 * @returns {string} 唯一标识符
 */
const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

/**
 * 模拟API延迟
 * @param {number} ms - 延迟毫秒数
 * @returns {Promise<void>}
 */
const delay = (ms: number): Promise<void> => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

/**
 * 创建RSS Store
 */
export const useRSSStore = defineStore('rss', {
  state: (): RSSStoreState => ({
    // 初始状态
    feeds: [],
    selectedFeedId: null,
    feedsLoading: false,
    
    articles: [],
    selectedArticleId: null,
    articlesLoading: false,
    totalArticles: 0,
    currentPage: 1,
    
    categories: [
      {
        id: 'default',
        name: '默认分类',
        color: '#90CAF9',
        icon: 'folder',
        order: 0,
        createdAt: new Date(),
        feedCount: 0,
      },
    ],
    selectedCategoryId: null,
    
    searchFilter: { ...defaultSearchFilter },
    settings: { ...defaultUserSettings },
  }),

  getters: {
    /**
     * 获取当前选中的RSS源
     * @returns {RSSFeed | undefined} 当前选中的RSS源
     */
    selectedFeed: (state): RSSFeed | undefined => {
      return state.feeds.find(feed => feed.id === state.selectedFeedId);
    },

    /**
     * 获取当前选中的文章
     * @returns {Article | undefined} 当前选中的文章
     */
    selectedArticle: (state): Article | undefined => {
      return state.articles.find(article => article.id === state.selectedArticleId);
    },

    /**
     * 获取当前选中的分类
     * @returns {Category | undefined} 当前选中的分类
     */
    selectedCategory: (state): Category | undefined => {
      return state.categories.find(category => category.id === state.selectedCategoryId);
    },

    /**
     * 获取过滤后的文章列表
     * @returns {Article[]} 过滤后的文章列表
     */
    filteredArticles: (state): Article[] => {
      let filtered = [...state.articles];
      
      // 关键词搜索
      if (state.searchFilter.keyword) {
        const keyword = state.searchFilter.keyword.toLowerCase();
        filtered = filtered.filter(article => 
          article.title.toLowerCase().includes(keyword) ||
          (article.summary && article.summary.toLowerCase().includes(keyword))
        );
      }
      
      // RSS源过滤
      if (state.searchFilter.feedIds.length > 0) {
        filtered = filtered.filter(article => 
          state.searchFilter.feedIds.includes(article.feedId)
        );
      }
      
      // 未读过滤
      if (state.searchFilter.unreadOnly) {
        filtered = filtered.filter(article => !article.isRead);
      }
      
      // 收藏过滤
      if (state.searchFilter.favoriteOnly) {
        filtered = filtered.filter(article => article.isFavorite);
      }
      
      // 排序
      filtered.sort((a, b) => {
        const aValue = a[state.searchFilter.sortBy as keyof Article];
        const bValue = b[state.searchFilter.sortBy as keyof Article];
        
        if (state.searchFilter.sortOrder === 'desc') {
          return aValue > bValue ? -1 : 1;
        } else {
          return aValue < bValue ? -1 : 1;
        }
      });
      
      return filtered;
    },

    /**
     * 获取未读文章数量
     * @returns {number} 未读文章数量
     */
    unreadCount: (state): number => {
      return state.articles.filter(article => !article.isRead).length;
    },
  },

  actions: {
    /**
     * 添加RSS源
     * @param {Omit<RSSFeed, 'id' | 'createdAt' | 'updatedAt' | 'articleCount' | 'unreadCount'>} feedData - RSS源数据
     * @returns {Promise<RSSFeed>} 添加的RSS源
     */
    async addFeed(feedData: Omit<RSSFeed, 'id' | 'createdAt' | 'updatedAt' | 'articleCount' | 'unreadCount'>): Promise<RSSFeed> {
      try {
        this.feedsLoading = true;
        
        // 调用后端API添加RSS源
        const response = await feedsApi.addFeed({
          title: feedData.title,
          url: feedData.url,
          description: feedData.description,
          link: feedData.link,
        });
        
        if (!response.success) {
          throw new Error(response.message || '添加RSS源失败');
        }
        
        // 转换后端数据格式
        const newFeed = dataTransform.backendFeedToFrontend(response.data);
        
        this.feeds.push(newFeed);
        
        // 更新分类的RSS源数量
        const category = this.categories.find(cat => cat.id === newFeed.categoryId);
        if (category) {
          category.feedCount++;
        }
        
        console.log('RSS源添加成功:', newFeed);
        
        // 立即刷新RSS源获取文章
        try {
          await this.refreshFeed(newFeed.id);
        } catch (error) {
          console.warn('获取RSS内容失败，但RSS源已添加:', error);
        }
        
        return newFeed;
      } catch (error) {
        console.error('添加RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 更新RSS源
     * @param {string} id - RSS源ID
     * @param {Partial<RSSFeed>} updates - 更新数据
     * @returns {Promise<void>}
     */
    async updateFeed(id: string, updates: Partial<RSSFeed>): Promise<void> {
      try {
        this.feedsLoading = true;
        
        // 调用后端API更新RSS源
        const response = await feedsApi.updateFeed(parseInt(id), {
          title: updates.title,
          url: updates.url,
          description: updates.description,
          link: updates.link,
          isActive: updates.isActive,
        });
        
        if (!response.success) {
          throw new Error(response.message || '更新RSS源失败');
        }
        
        // 更新本地数据
        const feedIndex = this.feeds.findIndex(feed => feed.id === id);
        if (feedIndex !== -1) {
          this.feeds[feedIndex] = dataTransform.backendFeedToFrontend(response.data);
          console.log('RSS源更新成功:', this.feeds[feedIndex]);
        }
      } catch (error) {
        console.error('更新RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 删除RSS源
     * @param {string} id - RSS源ID
     * @returns {Promise<void>}
     */
    async deleteFeed(id: string): Promise<void> {
      try {
        this.feedsLoading = true;
        
        // 调用后端API删除RSS源
        const response = await feedsApi.deleteFeed(parseInt(id));
        
        if (!response.success) {
          throw new Error(response.message || '删除RSS源失败');
        }
        
        const feedIndex = this.feeds.findIndex(feed => feed.id === id);
        if (feedIndex !== -1) {
          const feed = this.feeds[feedIndex];
          this.feeds.splice(feedIndex, 1);
          
          // 删除相关文章
          this.articles = this.articles.filter(article => article.feedId !== id);
          
          // 更新分类的RSS源数量
          const category = this.categories.find(cat => cat.id === feed.categoryId);
          if (category && category.feedCount > 0) {
            category.feedCount--;
          }
          
          // 如果删除的是当前选中的RSS源，清除选中状态
          if (this.selectedFeedId === id) {
            this.selectedFeedId = null;
          }
          
          console.log('RSS源删除成功:', id);
        }
      } catch (error) {
        console.error('删除RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 加载RSS源列表
     * @returns {Promise<void>}
     */
    async loadFeeds(): Promise<void> {
      try {
        this.feedsLoading = true;
        
        // 调用后端API获取RSS源列表
        const response = await feedsApi.getFeeds();
        
        if (!response.success) {
          throw new Error(response.message || '加载RSS源失败');
        }
        
        // 转换数据格式并更新状态
        this.feeds = response.data.content.map(feed => 
          dataTransform.backendFeedToFrontend(feed)
        );
        
        // 更新分类的RSS源数量
        const defaultCategory = this.categories.find(cat => cat.id === 'default');
        if (defaultCategory) {
          defaultCategory.feedCount = this.feeds.length;
        }
        
        console.log('RSS源加载成功:', this.feeds.length);
      } catch (error) {
        console.error('加载RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 设置选中的RSS源
     * @param {string | null} feedId - RSS源ID
     */
    async setSelectedFeed(feedId: string | null): Promise<void> {
      this.selectedFeedId = feedId;
      this.currentPage = 1; // 重置页码
      
      // 更新搜索过滤器中的feedIds
      if (feedId) {
        this.searchFilter.feedIds = [feedId];
      } else {
        this.searchFilter.feedIds = [];
      }
      
      // 自动加载对应RSS源的文章
      await this.loadArticles(1);
    },

    /**
     * 解析RSS XML内容
     * @param {string} xmlText - RSS XML文本
     * @param {string} feedId - RSS源ID
     * @returns {Article[]} 解析后的文章列表
     */
    parseRSSXML(xmlText: string, feedId: string): Article[] {
      try {
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
        
        // 检查解析错误
        const parseError = xmlDoc.querySelector('parsererror');
        if (parseError) {
          throw new Error('RSS XML解析失败: ' + parseError.textContent);
        }
        
        const articles: Article[] = [];
        
        // 尝试解析RSS 2.0格式
        let items = xmlDoc.querySelectorAll('item');
        
        // 如果没有找到item，尝试解析Atom格式
        if (items.length === 0) {
          items = xmlDoc.querySelectorAll('entry');
        }
        
        items.forEach((item, index) => {
          if (index >= 20) return; // 限制最多20篇文章
          
          const title = item.querySelector('title')?.textContent?.trim() || '无标题';
          const description = item.querySelector('description')?.textContent?.trim() || 
                            item.querySelector('summary')?.textContent?.trim() || 
                            item.querySelector('content')?.textContent?.trim() || '';
          
          const link = item.querySelector('link')?.textContent?.trim() || 
                      item.querySelector('link')?.getAttribute('href') || '';
          
          const pubDateText = item.querySelector('pubDate')?.textContent?.trim() || 
                             item.querySelector('published')?.textContent?.trim() || 
                             item.querySelector('updated')?.textContent?.trim();
          
          const publishedAt = pubDateText ? new Date(pubDateText) : new Date();
          
          const author = item.querySelector('author')?.textContent?.trim() || 
                        item.querySelector('dc\\:creator')?.textContent?.trim() || 
                        item.querySelector('creator')?.textContent?.trim() || '';
          
          // 提取图片URL
          let imageUrl = '';
          const enclosure = item.querySelector('enclosure[type^="image"]');
          if (enclosure) {
            imageUrl = enclosure.getAttribute('url') || '';
          } else {
            // 从描述中提取图片
            const imgMatch = description.match(/<img[^>]+src=["']([^"']+)["'][^>]*>/i);
            if (imgMatch) {
              imageUrl = imgMatch[1];
            }
          }
          
          // 处理图片URL，使用代理服务器解决跨域问题
          if (imageUrl && !imageUrl.startsWith('data:')) {
            // 如果是相对路径，转换为绝对路径
            if (imageUrl.startsWith('/')) {
              const feedUrl = new URL(this.feeds.find(f => f.id === feedId)?.url || '');
              imageUrl = `${feedUrl.protocol}//${feedUrl.host}${imageUrl}`;
            }
            // 使用图片代理函数
            imageUrl = this.getProxyImageUrl(imageUrl);
          }
          
          // 清理HTML标签
          const cleanDescription = description.replace(/<[^>]*>/g, '').substring(0, 300);
          
          const article: Article = {
            id: generateId(),
            feedId,
            title,
            summary: cleanDescription,
            content: description,
            link,
            publishedAt,
            author,
            isRead: false,
            isFavorite: false,
            tags: [],
            imageUrl: imageUrl || `https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=${encodeURIComponent(title.substring(0, 50))}&image_size=landscape_4_3`,
            createdAt: new Date(),
          };
          
          articles.push(article);
        });
        
        return articles;
      } catch (error) {
        console.error('RSS XML解析失败:', error);
        throw error;
      }
    },

    /**
     * 获取代理图片URL
     * @param {string} originalUrl - 原始图片URL
     * @returns {string} 代理后的图片URL
     */
    getProxyImageUrl(originalUrl: string): string {
      if (!originalUrl || originalUrl.startsWith('data:') || originalUrl.startsWith('/api/image-proxy')) {
        return originalUrl;
      }
      
      try {
        // 验证URL格式
        new URL(originalUrl);
        return `/api/image-proxy?url=${encodeURIComponent(originalUrl)}`;
      } catch (error) {
        console.warn('无效的图片URL:', originalUrl);
        return originalUrl;
      }
    },

    /**
     * 获取RSS内容（通过代理服务器解决CORS问题）
     * @param {string} rssUrl - RSS源URL
     * @returns {Promise<string>} RSS XML内容
     */
    async fetchRSSContent(rssUrl: string): Promise<string> {
      try {
        console.log('开始获取RSS内容:', rssUrl);
        
        // 首先尝试使用本地代理服务器
        try {
          const proxyUrl = `/api/proxy?url=${encodeURIComponent(rssUrl)}`;
          
          const response = await fetch(proxyUrl, {
            method: 'GET',
            headers: {
              'Accept': 'application/rss+xml, application/xml, text/xml, */*',
            },
          });
          
          if (!response.ok) {
            throw new Error(`代理服务器错误: ${response.status} ${response.statusText}`);
          }
          
          const rssContent = await response.text();
          console.log('通过本地代理获取RSS成功:', rssUrl);
          return rssContent;
        } catch (proxyError) {
          console.warn('本地代理失败，尝试备用方案:', proxyError);
          
          // 备用方案：使用其他CORS代理服务
          const fallbackProxies = [
            `https://cors-anywhere.herokuapp.com/${rssUrl}`,
            `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(rssUrl)}`,
          ];
          
          for (const fallbackUrl of fallbackProxies) {
            try {
              const response = await fetch(fallbackUrl, {
                method: 'GET',
                headers: {
                  'Accept': 'application/rss+xml, application/xml, text/xml, */*',
                  'X-Requested-With': 'XMLHttpRequest',
                },
              });
              
              if (response.ok) {
                const rssContent = await response.text();
                console.log('通过备用代理获取RSS成功:', fallbackUrl);
                return rssContent;
              }
            } catch (fallbackError) {
              console.warn('备用代理失败:', fallbackUrl, fallbackError);
              continue;
            }
          }
          
          throw new Error('所有代理服务都无法访问');
        }
      } catch (error) {
        console.error('获取RSS内容失败:', error);
        throw error;
      }
    },

    /**
     * 刷新RSS源
     * @param {string} feedId - RSS源ID
     * @returns {Promise<void>}
     */
    async refreshFeed(feedId: string): Promise<void> {
      try {
        this.feedsLoading = true;
        
        const feed = this.feeds.find(f => f.id === feedId);
        if (!feed) {
          throw new Error('RSS源不存在');
        }
        
        console.log('开始刷新RSS源:', feed.title);
        
        // 调用后端API刷新RSS源
        const response = await feedsApi.refreshFeed(parseInt(feedId));
        
        if (!response.success) {
          throw new Error(response.message || '刷新RSS源失败');
        }
        
        // 刷新成功后重新加载文章列表
        await this.loadArticles(1);
        
        // 重新获取RSS源信息以更新统计数据
        await this.loadFeeds();
        
        console.log(`RSS源刷新成功: ${feed.title}`);
      } catch (error) {
        console.error('刷新RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 刷新所有RSS源
     * @returns {Promise<void>}
     */
    async refreshAllFeeds(): Promise<void> {
      try {
        this.feedsLoading = true;

        
        // 调用后端API刷新所有RSS源
        const response = await feedsApi.refreshAllFeeds();
        
        if (!response.success) {
          throw new Error(response.message || '刷新所有RSS源失败');
        }
        
        // 刷新成功后重新加载数据
        await this.loadFeeds();
        await this.loadArticles(1);
        
        console.log('所有RSS源刷新完成');
      } catch (error) {
        console.error('刷新所有RSS源失败:', error);
        throw error;
      } finally {
        this.feedsLoading = false;
      }
    },

    /**
     * 加载文章列表
     * @param {number} page - 页码
     * @returns {Promise<void>}
     */
    async loadArticles(page: number = 1): Promise<void> {
      try {
        this.articlesLoading = true;
        
        // 构建查询参数
        const params: any = {
          page: page, // 后端使用1基索引
          size: this.settings.articlesPerPage,
          sortBy: this.searchFilter.sortBy,
          sortOrder: this.searchFilter.sortOrder,
        };
        
        // 添加过滤条件
        if (this.searchFilter.keyword) {
          params.keyword = this.searchFilter.keyword;
        }
        if (this.searchFilter.feedIds.length > 0) {
          params.feedId = parseInt(this.searchFilter.feedIds[0]); // 暂时只支持单个RSS源过滤
        }
        if (this.searchFilter.unreadOnly) {
          params.unreadOnly = true;
        }
        if (this.searchFilter.favoriteOnly) {
          params.favoriteOnly = true;
        }

        
        // 调用后端API获取文章列表
        const response = await articlesApi.getArticles(params);

        
        if (!response.success) {
          throw new Error(response.message || '加载文章失败');
        }
        
        const pageData = response.data;
        
        // 转换文章数据格式
        const articles = [];
        for (let i = 0; i < pageData.content.length; i++) {
          const article = pageData.content[i];
          try {
            const transformed = dataTransform.backendArticleToFrontend(article);
            articles.push(transformed);
          } catch (transformError) {
            console.error(`文章转换失败:`, {
              error: transformError,
              originalArticle: article,
              articleIndex: i
            });
            // 跳过有问题的文章，继续处理其他文章
            continue;
          }
        }

        
        if (page === 1) {
          // 第一页，重新加载
          this.articles = articles;
          this.currentPage = 1;
        } else {
          // 追加到现有列表
          this.articles.push(...articles);
        }
        
        this.currentPage = page;
        this.totalArticles = pageData.totalElements;

      } catch (error) {
        console.error('加载文章失败:', error);
        throw error;
      } finally {
        this.articlesLoading = false;
      }
    },

    /**
     * 标记文章为已读
     * @param {string} articleId - 文章ID
     * @returns {Promise<void>}
     */
    async markArticleAsRead(articleId: string): Promise<void> {
      try {
        const article = this.articles.find(a => a.id === articleId);
        if (!article || article.isRead) {
          return; // 文章不存在或已经是已读状态
        }
        
        // 调用后端API标记为已读
        const response = await articlesApi.markAsRead(parseInt(articleId));
        
        if (!response.success) {
          throw new Error(response.message || '标记文章已读失败');
        }
        
        // 更新本地状态
        article.isRead = true;
        
        // 更新RSS源的未读数量
        const feed = this.feeds.find(f => f.id === article.feedId);
        if (feed && feed.unreadCount > 0) {
          feed.unreadCount--;
        }
        
        console.log('文章标记为已读:', articleId);
      } catch (error) {
        console.error('标记文章已读失败:', error);
        throw error;
      }
    },

    /**
     * 切换文章收藏状态
     * @param {string} articleId - 文章ID
     * @returns {Promise<void>}
     */
    async toggleArticleFavorite(articleId: string): Promise<void> {
      try {
        const article = this.articles.find(a => a.id === articleId);
        if (!article) {
          throw new Error('文章不存在');
        }
        
        // 调用后端API切换收藏状态
        const { articlesApi } = await import('@/services/api');
        const articleIdNumber = parseInt(articleId, 10);
        
        if (isNaN(articleIdNumber)) {
          throw new Error('无效的文章ID');
        }
        
        try {
          // 调用后端API
          await articlesApi.toggleFavorite(articleIdNumber, article.isFavorite);
          
          // API调用成功后更新本地状态
          article.isFavorite = !article.isFavorite;
          
          console.log('文章收藏状态切换成功:', { 
            articleId, 
            isFavorite: article.isFavorite 
          });
        } catch (apiError) {
          // 如果后端API调用失败，回退到本地状态更新
          console.warn('后端收藏API调用失败，使用本地状态更新:', apiError);
          article.isFavorite = !article.isFavorite;
          
          console.log('文章收藏状态切换(本地):', { 
            articleId, 
            isFavorite: article.isFavorite 
          });
        }
      } catch (error) {
        console.error('切换文章收藏状态失败:', error);
        throw error;
      }
    },

    /**
     * 更新文章内容
     * @param {string} articleId - 文章ID
     * @param {string} content - 新的文章内容
     * @returns {Promise<void>}
     */
    async updateArticleContent(articleId: string, content: string): Promise<void> {
      try {
        const article = this.articles.find(a => a.id === articleId);
        if (article) {
          // 导入图片处理函数
          const { processImagesInHtml } = await import('@/utils/imageProxy');
          
          // 处理内容中的图片，优先使用data-original属性
          const processedContent = processImagesInHtml(content);
          
          article.content = processedContent;
          console.log('文章内容更新成功:', { articleId, contentLength: processedContent.length });
        }
      } catch (error) {
        console.error('更新文章内容失败:', error);
        throw error;
      }
    },

    /**
     * 更新或添加文章
     * @param {Article} articleData - 文章数据
     * @returns {Promise<void>}
     */
    async updateOrAddArticle(articleData: Article): Promise<void> {
      try {
        const existingIndex = this.articles.findIndex(a => a.id === articleData.id);
        
        if (existingIndex !== -1) {
          // 更新现有文章
          this.articles[existingIndex] = {
            ...this.articles[existingIndex],
            ...articleData,
          };
          console.log('文章更新成功:', { articleId: articleData.id });
        } else {
          // 添加新文章
          this.articles.unshift(articleData);
          console.log('文章添加成功:', { articleId: articleData.id });
        }
      } catch (error) {
        console.error('更新或添加文章失败:', error);
        throw error;
      }
    },

    /**
     * 设置选中的文章
     * @param {string | null} articleId - 文章ID
     */
    setSelectedArticle(articleId: string | null): void {
      this.selectedArticleId = articleId;
    },

    /**
     * 添加分类
     * @param {Omit<Category, 'id' | 'createdAt' | 'feedCount'>} categoryData - 分类数据
     * @returns {Promise<void>}
     */
    async addCategory(categoryData: Omit<Category, 'id' | 'createdAt' | 'feedCount'>): Promise<void> {
      try {
        await delay(300);
        
        const newCategory: Category = {
          ...categoryData,
          id: generateId(),
          createdAt: new Date(),
          feedCount: 0,
        };
        
        this.categories.push(newCategory);
        console.log('分类添加成功:', newCategory);
      } catch (error) {
        console.error('添加分类失败:', error);
        throw error;
      }
    },

    /**
     * 更新分类
     * @param {string} id - 分类ID
     * @param {Partial<Category>} updates - 更新数据
     * @returns {Promise<void>}
     */
    async updateCategory(id: string, updates: Partial<Category>): Promise<void> {
      try {
        await delay(300);
        
        const categoryIndex = this.categories.findIndex(cat => cat.id === id);
        if (categoryIndex !== -1) {
          this.categories[categoryIndex] = {
            ...this.categories[categoryIndex],
            ...updates,
          };
          console.log('分类更新成功:', this.categories[categoryIndex]);
        }
      } catch (error) {
        console.error('更新分类失败:', error);
        throw error;
      }
    },

    /**
     * 删除分类
     * @param {string} id - 分类ID
     * @returns {Promise<void>}
     */
    async deleteCategory(id: string): Promise<void> {
      try {
        await delay(300);
        
        // 不能删除默认分类
        if (id === 'default') {
          throw new Error('不能删除默认分类');
        }
        
        const categoryIndex = this.categories.findIndex(cat => cat.id === id);
        if (categoryIndex !== -1) {
          // 将该分类下的RSS源移动到默认分类
          this.feeds.forEach(feed => {
            if (feed.categoryId === id) {
              feed.categoryId = 'default';
            }
          });
          
          // 更新默认分类的RSS源数量
          const defaultCategory = this.categories.find(cat => cat.id === 'default');
          if (defaultCategory) {
            const deletedCategory = this.categories[categoryIndex];
            defaultCategory.feedCount += deletedCategory.feedCount;
          }
          
          this.categories.splice(categoryIndex, 1);
          
          // 如果删除的是当前选中的分类，清除选中状态
          if (this.selectedCategoryId === id) {
            this.selectedCategoryId = null;
          }
          
          console.log('分类删除成功:', id);
        }
      } catch (error) {
        console.error('删除分类失败:', error);
        throw error;
      }
    },

    /**
     * 设置选中的分类
     * @param {string | null} categoryId - 分类ID
     */
    setSelectedCategory(categoryId: string | null): void {
      this.selectedCategoryId = categoryId;
    },

    /**
     * 更新搜索过滤器
     * @param {Partial<SearchFilter>} filter - 过滤器更新数据
     */
    updateSearchFilter(filter: Partial<SearchFilter>): void {
      this.searchFilter = {
        ...this.searchFilter,
        ...filter,
      };
      this.currentPage = 1; // 重置页码
    },

    /**
     * 重置搜索过滤器
     */
    resetSearchFilter(): void {
      this.searchFilter = { ...defaultSearchFilter };
      this.currentPage = 1;
    },

    /**
     * 更新用户设置
     * @param {Partial<UserSettings>} settings - 设置更新数据
     */
    updateSettings(settings: Partial<UserSettings>): void {
      this.settings = {
        ...this.settings,
        ...settings,
      };
      console.log('用户设置更新:', settings);
    },

    /**
     * 导入数据
     * @param {any} data - 导入的数据
     * @returns {Promise<void>}
     */
    async importData(data: any): Promise<void> {
      try {
        await delay(1000);
        
        if (data.feeds) {
          this.feeds = data.feeds;
        }
        if (data.categories) {
          this.categories = data.categories;
        }
        if (data.settings) {
          this.settings = { ...this.settings, ...data.settings };
        }
        
        console.log('数据导入成功');
      } catch (error) {
        console.error('数据导入失败:', error);
        throw error;
      }
    },

    /**
     * 清除所有数据
     * @returns {Promise<void>}
     */
    async clearAllData(): Promise<void> {
      try {
        await delay(500);
        
        this.feeds = [];
        this.articles = [];
        this.categories = [
          {
            id: 'default',
            name: '默认分类',
            color: '#90CAF9',
            icon: 'folder',
            order: 0,
            createdAt: new Date(),
            feedCount: 0,
          },
        ];
        this.selectedFeedId = null;
        this.selectedArticleId = null;
        this.selectedCategoryId = null;
        this.searchFilter = { ...defaultSearchFilter };
        this.currentPage = 1;
        this.totalArticles = 0;
        
        console.log('所有数据已清除');
      } catch (error) {
        console.error('清除数据失败:', error);
        throw error;
      }
    },

    /**
     * 初始化数据
     * @returns {Promise<void>}
     */
    async initialize(): Promise<void> {
      try {
        
        
        // 加载RSS源列表
        await this.loadFeeds();
        
        // 如果没有RSS源，添加一些示例数据
        if (this.feeds.length === 0) {
          
          const sampleFeeds: Omit<RSSFeed, 'id' | 'createdAt' | 'updatedAt' | 'articleCount' | 'unreadCount'>[] = [
            {
              title: '少数派',
              url: 'https://sspai.com/feed',
              description: '高品质数字生活指南',
              link: 'https://sspai.com',
              categoryId: 'default',
              isActive: true,
              favicon: 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=sspai%20logo%20icon&image_size=square',
            },
            {
              title: 'IT之家',
              url: 'https://www.ithome.com/rss/',
              description: 'IT科技资讯网站',
              link: 'https://www.ithome.com',
              categoryId: 'default',
              isActive: true,
              favicon: 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=ithome%20tech%20news%20icon&image_size=square',
            },
          ];
          
          for (const feedData of sampleFeeds) {
            try {
              await this.addFeed(feedData);
            } catch (error) {
              // 忽略示例RSS源添加失败
            }
          }
        }
        
        // 加载初始文章
        await this.loadArticles(1);

      } catch (error) {
        console.error('初始化RSS Store失败:', error);
        // 初始化失败时不抛出错误，允许应用继续运行
      }
    },
  },
});